<!-- O2 血氧仪设备 -->
<template>
	<view class="pageview">
		<firstConnect v-if="isFirst" :device-type="deviceType" :deviceStatus="deviceStatus" @startUse="startUse"
			@retry="retry"></firstConnect>
		<template v-else>
			<view class="toptip flex align-center justify-between" v-if="!isConnected">
				<text>{{ blueState ? '当前设备未连接，请连接设备' : '需要开启蓝牙，连接设备' }}</text>
				<view class="btn flex align-center" @click="devicesDiscovery" v-if="blueState">
					<u-loading-icon color="#fff" :show="deviceStatus == 0 || deviceStatus == 1"></u-loading-icon>
					<text>去连接</text>
				</view>
			</view>
			<view class="startWork">
				<O2Chart ref="O2Chart"></O2Chart>
				<view v-if="isConnected && deviceData.spo2 > 0">
					<u-button shape="circle" type="primary" text="保存本次数据" @click="save"></u-button>
					<view class="stepbox"></view>
					<view class="flex result">
						<view class="flex-sub item">
							<view>血氧</view>
							<view class="u-margin-top-20">
								<text class="num">{{ deviceData.spo2 }}</text>
								<text class="unit">%</text>
							</view>
						</view>
						<view class="flex-sub item">
							<view>脉率</view>
							<view class="u-margin-top-20">
								<text class="num">{{ deviceData.pr }}</text>
								<text class="unit">次/分钟</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</template>
	</view>
</template>

<script>
	import {
		ab2str,
		formatNum,
		formatSecond,
		chunk
	} from '@/utils/util';
	const O2Protocol = require('@/utils/ble_devices/o2');
	const O2Builder = {
		// 注意这里的this是实例化后的O2对象，而不是page
		notifyServiceId: '14839AC4-7D7E-415C-9A42-167340CF2339',
		deviceFoundFilter: item => /(O2)/.test(item.name),
		connectionStateChange: function(res) {
			console.log('O2连接状态改变', res);
			this.connectionState = res.connected;
		},
		characteristicValueChange: function(res) {
			if (res.value) {
				// 开始解析数据
				if (res.value !== this.oldCallbackData) {
					//可能会有重复的包
					this.oldCallbackData = res.value;
					// 而且微信返回的value是ArrayBuffer，所以同样要先转换成str
					this.parseData(ab2str(res.value));
				}
			}
		}
	};

	const O2 = new O2Protocol(O2Builder);
	let foundTimer = null;
	import firstConnect from './components/firstConnect';
	import O2Chart from './components/O2Chart';
	import stompMixin from '@/common/stompMixin.js';
	import mixin from './mixin.js';
	import {
		mapState
	} from 'vuex';
	export default {
		mixins: [stompMixin, mixin],
		data() {
			return {
				isConnected: false, // 是否连接设备
				devicesDiscovered: [], // 设备列表
				connectedDevice: null, // 当前连接设备
				deviceType: 'O2Ring',
				deviceTypeId: '',
				isFirst: true,
				deviceStatus: -1, //-1 初始化，1查找设备 2连接设备，3没有找到设备
				deviceData: '',
				deviceMac: '',
				blueState: false //蓝牙状态
			};
		},
		computed: {
			...mapState(['userInfo', 'curAccount'])
		},
		components: {
			firstConnect,
			O2Chart
		},
		onLoad(optioin) {
			this.deviceType = optioin.deviceType;
			if (optioin.deviceTypeId) {
				this.deviceTypeId = optioin.deviceTypeId;
				this.isFirst = true;
			} else {
				this.deviceMac = optioin.deviceMac;
				this.isFirst = false;
			}
			// 使用 watch 方法监听 message 属性的变化
			const appInstance = getApp();
			appInstance.watch(this, O2, {
				//蓝牙配置状态
				adapterState: function(newVal) {
					if (newVal && !this.blueState) {
						this.blueState = true; //设置蓝牙初始化成功了
						this.deviceStatus = -1;
						if (this.isFirst) {
							this.devicesDiscovery();
						}
					}
				},
				foundDevices: function(newVal) {
					this.devicesDiscovered = newVal;
					if (this.devicesDiscovered.length > 0 && !this.isConnected) {
						let index = -1;
						if (this.deviceMac) {
							index = this.devicesDiscovered.findIndex(item => item.deviceId == this.deviceMac);
						} else {
							if (this.deviceType == 'O2Ring') {
								index = this.devicesDiscovered.findIndex(item => /(O2Ring)/.test(item.name));
							} else {
								index = this.devicesDiscovered.findIndex(item => /(O2M)/.test(item.name));
							}
						}
						console.log('index', index);
						if (index > -1) {
							this.deviceStatus = 1;
							this.connectToDevice(index);
							clearTimeout(foundTimer);
							foundTimer = null;
						}
					}
				},
				connectedDevice: function(newVal) {
					this.isConnected = !!newVal;
					this.connectedDevice = newVal;
					this.deviceStatus = 2;
					if (this.isFirst) {
						this.addDevice();
					} else {
						this.getRealTimeEcg();
					}
				},
				allWaveData: function(newVal) {
					if (newVal.spo2 <= 100) {
						this.deviceData = newVal;
						this.$refs.O2Chart && this.$refs.O2Chart.getServerData(newVal.spo2);
					}
				},
				//设备连接状态
				connectionState: function(newVal) {
					this.deviceStatus = newVal ? 2 : 3;
					//表示链接断开了
					if (this.deviceStatus == 3) {
						O2.foundDevices = [];
					}
				}
			});
			// 开启监听ER2属性
			// this.watchER2()
			// 初始化蓝牙
			O2.init();
		},
		onUnload() {
			// 不在当前页面的时候断开连接
			this.disconnectToDevice();
			// 关闭实时指令timer
			this.stopRealTimeEcg();
			//如果还在查找设备，先停止查找
			if (foundTimer || this.deviceStatus == 0) {
				this.clearfoundTimer();
			}
		},

		methods: {
			// 搜索周围设备
			devicesDiscovery() {
				this.deviceStatus = 0;
				O2.startDevicesDiscovery();
				//10s没有找到设备，就提示没有发现设备
				foundTimer = setTimeout(() => {
					this.clearfoundTimer();
				}, 5000);
			},
			// 连接指定设备
			connectToDevice(index) {
				O2.stopDevicesDiscovery();
				if (this.isConnected) {
					return;
				}
				const targetDevice = this.devicesDiscovered[index];
				O2.connectToDevice(targetDevice).then(() => {
					// 连接成功后获取设备信息
					const cmd = O2.generateCmd('14', '00', '');
					O2.writeValue(cmd);
				});
			},
			// 断开当前连接设备
			disconnectToDevice() {
				O2.disconnectToDevice();
			},
			startUse() {
				this.isFirst = false;
				this.getRealTimeEcg();
			},
			// 开始实时监测
			getRealTimeEcg() {
				if (this.isConnected) {
					const that = this;
					// 实时指令要持续发送，但是频率不能过高，500ms合适
					if (!O2.EcgCmdTimer) {
						O2.EcgCmdTimer = setInterval(() => {
							const EcgCmd = O2.generateCmd('17', '00', '');
							O2.writeValue(EcgCmd);
						}, 500);
					}
				}
			},
			// 停止实时监听
			stopRealTimeEcg() {
				if (O2.EcgCmdTimer) {
					clearInterval(O2.EcgCmdTimer);
					O2.EcgCmdTimer = null;
				}
			},
			retry() {
				this.deviceStatus = 0;
				this.devicesDiscovery();
			},
			// addDevice() {
			// 	this.$postAction(this.$deviceapi.addDevice, {
			// 		bindState: 1,
			// 		deviceTypeId: this.deviceTypeId,
			// 		userId: this.userInfo.userId,
			// 		devName: this.connectedDevice.name,
			// 		mac: this.connectedDevice.deviceId
			// 	});
			// },
			save() {
				this.send(
					JSON.stringify({
						detailId: this.curAccount.detailId,
						type: this.deviceType,
						data: this.deviceData
					})
				);
				uni.showToast({
					title: '保存成功',
					icon: 'none'
				})
			},
			clearfoundTimer() {
				O2.stopDevicesDiscovery();
				clearTimeout(foundTimer);
				foundTimer = null;
				this.deviceStatus = 3;
			}
		}
	};
</script>

<style scoped lang="scss">
	.pageview {
		background: #f2f2f2;
		height: 100vh;
	}

	.startWork {
		width: 600upx;
		margin: 0 auto;
		padding-top: 180upx;

		.imgbox {
			width: 400upx;
			margin: 0 auto 70upx;
		}

		.tip {
			text-align: center;
			margin-bottom: 10upx;
		}

		.stepbox {
			margin-top: 50upx;
		}

		.result {
			background: #fff;
			border-radius: 16upx;
			font-size: 28upx;
			color: #a5adae;
			padding: 30upx;
			margin-top: 50upx;

			.item {
				padding: 0 16upx;
			}

			.num {
				color: #243138;
				font-size: 46upx;
				font-weight: bold;
			}

			.unit {
				color: #374547;
				font-size: 24upx;
				margin-left: 10upx;
			}
		}
	}

	.toptip {
		background: #fff;
		padding: 20upx;
		position: absolute;
		top: 0;
		left: 0;
		right: 0;

		.btn {
			background: $u-primary;
			padding: 0 20upx;
			color: #fff;
			border-radius: 50upx;
			line-height: 60upx;
		}
	}
</style>